//
//  SEGNewBillManager.m
//  SEGUhomePropertyBaseService
//
//  Created by Clavis on 2019/2/26.
//  Copyright © 2019 刘山. All rights reserved.
//

#import "SEGNewBillManager.h"
#import "SEGBillMonthModel.h"
#import "SEGOwesMonthDetailModel.h"
#import "SEGBillUrlList.h"

@implementation SEGNewBillManager

/**
 请求指定月份范围账单列表
 
 @param params 可传查询的日期范围
 @param finished 回调处理
 */
- (void)requestBillListWithParamsDic:(NSDictionary *)params finished:(SEGRequestCallBack)finished {
    WeakSelf;
    [SEGHTTPBusinessManager seg_requestJSONWithMethod:POST URLString:kGetSpecifyMonthBillList parameters:params finished:^(BOOL isSuccessed, id result, NSString *codeType, NSString *errorMessage) {
        
        if (!isSuccessed) {
            finished(NO, codeType, errorMessage);
            return;
        }
        
        if (![result valueForKey:@"data"] || ![[result valueForKey:@"data"] isKindOfClass:[NSDictionary class]]) {
            finished(NO, codeType, kNetworkErrorMessage);
            return;
        }
        
        NSArray *billDicArray = result[@"data"][@"cycleInfo"];
        NSMutableDictionary<NSNumber *, NSMutableArray<SEGBillMonthModel *>*> *billYearDic = [[NSMutableDictionary alloc] init];
        NSMutableArray<NSNumber *> *yearArray = [NSMutableArray array];
        
        for (NSDictionary *billDic in billDicArray) {
            SEGBillMonthModel *monthModel = [SEGBillMonthModel yy_modelWithDictionary:billDic];
            monthModel.cycleAmount = billDic[@"acctAmount"];
            
            NSMutableArray<SEGOwesMonthDetailModel *> *billDetails = [NSMutableArray array];
            for (NSDictionary *oweDetailDic in billDic[@"detail"]) {
                SEGOwesMonthDetailModel *oweDetailModel = [SEGOwesMonthDetailModel yy_modelWithDictionary:oweDetailDic];
                [billDetails addObject:oweDetailModel];
                
                // 计算年份月份
                NSString *billCycle = billDic[@"billCycle"];
                if (billCycle.length >= 6) {
                    monthModel.billYear = [[billCycle substringToIndex:4] integerValue];
                    monthModel.billMonth = [[billCycle substringWithRange:NSMakeRange(4, 2)] integerValue];
                }
            }
            monthModel.billDetails = billDetails;
            
            // 根据年份去取字典的值
            NSMutableArray *billMonthModelArray = [NSMutableArray arrayWithArray:[billYearDic objectForKey:@(monthModel.billYear)]];
            [billMonthModelArray addObject:monthModel];
            [billYearDic setObject:billMonthModelArray forKey:@(monthModel.billYear)];
            
            // 添加年份到年份数组
            BOOL isExist = NO;
            for (NSNumber *year in yearArray) {
                if (year.integerValue == monthModel.billYear) {
                    isExist = YES;
                    break;
                }
            }
            if (!isExist) {
                [yearArray addObject:@(monthModel.billYear)];
            }
        }
        
        weakSelf.billYearDic = billYearDic;
        weakSelf.allYears = [yearArray copy];
        finished(YES, codeType, errorMessage);
    }];
}


/**
 请求全部的欠费账单列表

 @param params 参数
 @param finished 回调
 */
- (void)requestOweBillListWithParamsDic:(NSDictionary *)params finished:(SEGRequestCallBack)finished {
    // 欠费接口
    WeakSelf;
    [SEGHTTPBusinessManager seg_requestJSONWithMethod:POST URLString:kGetALLOweBillList parameters:params finished:^(BOOL isSuccessed, id result, NSString *codeType, NSString *errorMessage) {
        if (!isSuccessed) {
            finished(NO, codeType, errorMessage);
            return;
        }
        
        if (![result valueForKey:@"data"] || ![[result valueForKey:@"data"] isKindOfClass:[NSDictionary class]]) {
            finished(NO, codeType, kNetworkErrorMessage);
            return;
        }
        
        // 计算欠费的总金额
        weakSelf.oweAmount = [result[@"data"][@"acctAmount"] doubleValue] * MoneyRateChange;
        
        NSArray *billDicArray = result[@"data"][@"billDetail"];
        
        NSMutableDictionary<NSNumber *, NSMutableArray<SEGBillMonthModel *>*> *billYearDic = [[NSMutableDictionary alloc] init];
        NSMutableArray<NSNumber *> *yearArray = [NSMutableArray array];
        
        for (NSDictionary *billDic in billDicArray) {
            SEGBillMonthModel *monthModel = [SEGBillMonthModel yy_modelWithDictionary:billDic];
            
            NSMutableArray<SEGOwesMonthDetailModel *> *billDetails = [NSMutableArray array];
            for (NSDictionary *oweDetailDic in billDic[@"monthDetail"]) {
                SEGOwesMonthDetailModel *oweDetailModel = [SEGOwesMonthDetailModel yy_modelWithDictionary:oweDetailDic];
                [billDetails addObject:oweDetailModel];
            }
            monthModel.billDetails = billDetails;
            
            // 计算年份月份
            NSString *billCycle = billDic[@"billingCycle"];
            if (billCycle.length >= 6) {
                monthModel.billYear = [[billCycle substringToIndex:4] integerValue];
                monthModel.billMonth = [[billCycle substringWithRange:NSMakeRange(4, 2)] integerValue];
            }
            
            // 根据年份去取字典的值
            NSMutableArray *billMonthModelArray = [NSMutableArray arrayWithArray:[billYearDic objectForKey:@(monthModel.billYear)]];
            [billMonthModelArray addObject:monthModel];
            [billYearDic setObject:billMonthModelArray forKey:@(monthModel.billYear)];
            
            // 添加年份到年份数组
            BOOL isExist = NO;
            for (NSNumber *year in yearArray) {
                if (year.integerValue == monthModel.billYear) {
                    isExist = YES;
                    break;
                }
            }
            if (!isExist) {
                [yearArray addObject:@(monthModel.billYear)];
            }
         }
        
        weakSelf.billYearDic = billYearDic;
        weakSelf.allYears = [yearArray copy];
        finished(YES, codeType, errorMessage);
    }];
}


/**
 查询预缴规则

 @param params 参数
 @param finished 回调
 */
- (void)requestDiscountRuleWithParamsDic:(NSDictionary *)params finished:(SEGRequestCallBack)finished {
    WeakSelf;
    [SEGHTTPBusinessManager seg_requestJSONWithMethod:POST URLString:kGetBillDiscountRule parameters:params finished:^(BOOL isSuccessed, id result, NSString *codeType, NSString *errorMessage) {
        if (!isSuccessed) {
            finished(NO, codeType, errorMessage);
            return;
        }
        
        if (![result objectForKey:@"data"] || ![[result objectForKey:@"data"] isKindOfClass:[NSDictionary class]]) {
            finished(NO, codeType, kNetworkErrorMessage);
            return;
        }
        
        NSDictionary *dataDic = result[@"data"];
        weakSelf.discountArray = [[NSMutableArray alloc] init];
        for (NSDictionary *subFeeDic in dataDic[@"billDetail"]) {
            SEGOwesDisFeeModel *model = [SEGOwesDisFeeModel yy_modelWithDictionary:subFeeDic];
            [weakSelf.discountArray addObject:model];
        }
        
        weakSelf.feeItemArray = [[NSMutableArray alloc] init];
        for (NSDictionary *subFeeDic in dataDic[@"feeItemTypeInfo"]) {
            SEGBillFeeItemModel *model = [SEGBillFeeItemModel yy_modelWithDictionary:subFeeDic];
            [weakSelf.feeItemArray addObject:model];
        }
        
        finished(YES, codeType, errorMessage);
    }];
}


/**
 查询预缴账单

 @param params 参数
 @param finished 回调
 */
- (void)requestFutureBillListWithParamsDic:(NSDictionary *)params finished:(SEGRequestCallBack)finished {
    WeakSelf;
    [SEGHTTPBusinessManager seg_requestJSONWithMethod:POST URLString:kGetFutureBillList parameters:params finished:^(BOOL isSuccessed, id result, NSString *codeType, NSString *errorMessage) {
        if (!isSuccessed) {
            finished(NO, codeType, errorMessage);
            return;
        }
        
        if (![result valueForKey:@"data"] || ![[result valueForKey:@"data"] isKindOfClass:[NSDictionary class]]) {
            finished(NO, codeType, kNetworkErrorMessage);
            return;
        }
        
        // 计算欠费的总金额
        weakSelf.oweAmount = [result[@"data"][@"acctAmount"] doubleValue] * MoneyRateChange;
        // 解析缴费当前的优惠信息
        SEGOwesDisFeeModel *discountModel =  [SEGOwesDisFeeModel yy_modelWithDictionary:result[@"data"]];
        weakSelf.payDiscount = discountModel;
        // 解析缴费所有的优惠信息
        weakSelf.payDiscountInfoArray = [[NSMutableArray alloc] init];
        for (NSDictionary *disInfoDic in result[@"data"][@"disInfo"]) {
            SEGBillPaymentDiscInfoModel *disInfoModel = [SEGBillPaymentDiscInfoModel yy_modelWithDictionary:disInfoDic];
            [weakSelf.payDiscountInfoArray addObject:disInfoModel];
        }
        
        NSArray *billDicArray = result[@"data"][@"billDetail"];
        NSMutableArray<SEGBillMonthModel *> *billMonthsArray = [NSMutableArray array];
        
        for (NSDictionary *billMonthDic in billDicArray) {
            SEGBillMonthModel *monthModel = [SEGBillMonthModel yy_modelWithDictionary:billMonthDic];
            NSMutableArray<SEGOwesMonthDetailModel *> *billDetails = [NSMutableArray array];
            for (NSDictionary *oweDetailDic in billMonthDic[@"monthDetail"]) {
                SEGOwesMonthDetailModel *oweDetailModel = [SEGOwesMonthDetailModel yy_modelWithDictionary:oweDetailDic];
                oweDetailModel.isSelected = YES;
                [billDetails addObject:oweDetailModel];
            }
            monthModel.billDetails = billDetails;
            monthModel.isSelect = YES;
            
            // 计算年份月份
            NSString *billCycle = billMonthDic[@"billingCycle"];
            if (billCycle.length >= 6) {
                monthModel.billYear = [[billCycle substringToIndex:4] integerValue];
                monthModel.billMonth = [[billCycle substringWithRange:NSMakeRange(4, 2)] integerValue];
            }
            [billMonthsArray addObject:monthModel];
        }
        
        weakSelf.billMonthsArray = billMonthsArray;
        finished(YES, codeType, errorMessage);
    }];
}


/**
 查询缴费账单（和全部欠费的接口一致但数据结构不同）

 @param params 参数
 @param finished 回调
 */
- (void)requestPaymentBillListWithParamsDic:(NSDictionary *)params finished:(SEGRequestCallBack)finished {
    WeakSelf;
    [SEGHTTPBusinessManager seg_requestJSONWithMethod:POST URLString:kGetALLOweBillList parameters:params finished:^(BOOL isSuccessed, id result, NSString *codeType, NSString *errorMessage) {
        if (!isSuccessed) {
            finished(NO, codeType, errorMessage);
            return;
        }
        
        if (![result valueForKey:@"data"] || ![[result valueForKey:@"data"] isKindOfClass:[NSDictionary class]]) {
            finished(NO, codeType, kNetworkErrorMessage);
            return;
        }
        
        // 计算欠费的总金额
        weakSelf.oweAmount = [result[@"data"][@"acctAmount"] doubleValue] * MoneyRateChange;
        // 解析缴费当前的优惠信息
        SEGOwesDisFeeModel *discountModel =  [SEGOwesDisFeeModel yy_modelWithDictionary:result[@"data"]];
        weakSelf.payDiscount = discountModel;
        // 解析缴费所有的优惠信息
        weakSelf.payDiscountInfoArray = [[NSMutableArray alloc] init];
        for (NSDictionary *disInfoDic in result[@"data"][@"disInfo"]) {
            SEGBillPaymentDiscInfoModel *disInfoModel = [SEGBillPaymentDiscInfoModel yy_modelWithDictionary:disInfoDic];
            [weakSelf.payDiscountInfoArray addObject:disInfoModel];
        }
        
        NSArray *billDicArray = result[@"data"][@"billDetail"];
        NSMutableArray<SEGBillMonthModel *> *billMonthsArray = [NSMutableArray array];
        for (NSDictionary *billMonthDic in billDicArray) {
            SEGBillMonthModel *monthModel = [SEGBillMonthModel yy_modelWithDictionary:billMonthDic];
            NSMutableArray<SEGOwesMonthDetailModel *> *billDetails = [NSMutableArray array];
            for (NSDictionary *oweDetailDic in billMonthDic[@"monthDetail"]) {
                SEGOwesMonthDetailModel *oweDetailModel = [SEGOwesMonthDetailModel yy_modelWithDictionary:oweDetailDic];
                oweDetailModel.isSelected = YES;
                [billDetails addObject:oweDetailModel];
            }
            monthModel.billDetails = billDetails;
            monthModel.isSelect = YES;
            
            // 计算年份月份
            NSString *billCycle = billMonthDic[@"billingCycle"];
            if (billCycle.length >= 6) {
                monthModel.billYear = [[billCycle substringToIndex:4] integerValue];
                monthModel.billMonth = [[billCycle substringWithRange:NSMakeRange(4, 2)] integerValue];
            }
            [billMonthsArray addObject:monthModel];
        }
        
        weakSelf.billMonthsArray = billMonthsArray;
        finished(YES, codeType, errorMessage);
    }];
}


/**
 查询匹配的缴费优惠信息

 @param params 参数
 @param finished 回调
 */
- (void)requestMatchDiscountWithParamsDic:(NSDictionary *)params finished:(SEGRequestCallBack)finished {
    WeakSelf;
    self.payDiscount = nil; // 置空之前的数据
    [SEGHTTPBusinessManager seg_requestJSONWithMethod:POST URLString:kGetBillMatchDiscount parameters:params finished:^(BOOL isSuccessed, id result, NSString *codeType, NSString *errorMessage) {
        if (!isSuccessed) {
            finished(NO, codeType, errorMessage);
            return;
        }
        
        if (![result valueForKey:@"data"] || ![[result valueForKey:@"data"] isKindOfClass:[NSDictionary class]]) {
            finished(NO, codeType, kNetworkErrorMessage);
            return;
        }
        
        // 解析缴费当前的优惠信息
        SEGOwesDisFeeModel *discountModel =  [SEGOwesDisFeeModel yy_modelWithDictionary:result[@"data"]];
        weakSelf.payDiscount = discountModel;
        
        finished(YES, codeType, errorMessage);
    }];
}


/**
 请求缴费记录

 @param paramas 参数
 @param finished 回调
 */
- (void)requestBillPaymentRecoed:(NSDictionary *)paramas finished:(SEGRequestCallBack)finished {
    WeakSelf;
    [SEGHTTPBusinessManager seg_requestJSONWithMethod:POST URLString:kGetBillPaymentRecord parameters:paramas finished:^(BOOL isSuccessed, id result, NSString *codeType, NSString *errorMessage) {
        if (!isSuccessed) {
            finished(NO, codeType, errorMessage); //数据返回异常
            return;
        }
        if (![result valueForKey:@"data"] || ![[result valueForKey:@"data"] isKindOfClass:[NSDictionary class]]) {
            finished(NO, codeType, kNetworkErrorMessage); //数据返回异常
            return;
        }
        
        NSDictionary* data = [result valueForKey:@"data"];
        if (![data valueForKey:@"payLog"] || ![[data valueForKey:@"payLog"] isKindOfClass:[NSArray class]]) {
            finished(NO, codeType, kNetworkErrorMessage); //数据返回异常
            return;
        }
        
        NSArray* payLog = [data valueForKey:@"payLog"];
        if (!payLog || payLog.count <= 0) {
            finished(isSuccessed, codeType, errorMessage); //数据返回异常
            return;
        }
        
        NSMutableArray* arrM = [NSMutableArray array];
        for (NSDictionary* object in payLog) {
            SEGPayLogModel* model = [SEGPayLogModel initWithDictionary:object];
            [arrM addObject:model];
        }
        
        weakSelf.payRecodeModels = arrM;
        finished(YES, codeType, errorMessage);
    }];
}


/**
 请求缴费记录详情

 @param paramas 参数
 @param finished 回调
 */
- (void)requestBillPaymentRecoedDetail:(NSDictionary *)paramas finished:(SEGRequestCallBack)finished {
    WeakSelf;
    [SEGHTTPBusinessManager seg_requestJSONWithMethod:POST URLString:kGetBillPaymentRecordDetail parameters:paramas finished:^(BOOL isSuccessed, id result, NSString *codeType, NSString *errorMessage) {
        {
            if (!isSuccessed) {
                finished(NO, codeType, errorMessage); //数据返回异常
                return;
            }
            
            if (![result valueForKey:@"data"] || ![[result valueForKey:@"data"] isKindOfClass:[NSDictionary class]]) {
                finished(NO, codeType, kNetworkErrorMessage); //数据返回异常
                return;
            }
            
            NSDictionary* data = [result valueForKey:@"data"];
            if (![data valueForKey:@"detail"] || ![[data valueForKey:@"detail"] isKindOfClass:[NSArray class]]) {
                finished(NO, codeType, kNetworkErrorMessage); //数据返回异常
                return;
            }
            
            NSArray* detail = [data valueForKey:@"detail"];
            if (!detail || detail.count <= 0) {
                finished(NO, codeType, kNetworkErrorMessage); //数据返回异常
                return;
            }
            
            NSMutableArray<SEGOwesBillDetailModel*> *arrM = [NSMutableArray array];
            for (NSDictionary* object in detail) {
                SEGOwesBillDetailModel* model = [SEGOwesBillDetailModel initWithDictionary:object];
                [arrM addObject:model];
            }
            
            weakSelf.recordDetailModels = [weakSelf handelRecodeDetailData:arrM];
            finished(YES, codeType, errorMessage);
        }
    }];
}

// 处理缴费记录详情的数据
- (NSArray<SEGOwesBillDetailModel*> *)handelRecodeDetailData:(NSArray<SEGOwesBillDetailModel*>*)data {
    for (SEGOwesBillDetailModel* object in data) {
        
        NSMutableArray* arrM = [NSMutableArray array];
        //添加头部数据
        SEGOwesMonthDetailModel* head = [[SEGOwesMonthDetailModel alloc] init];
        head.type = SEGBillDetailDoLogicModelType_Head;
        [arrM addObject:head];
        
        //添加展示数据
        for (SEGOwesMonthDetailModel* object_ in object.billDetail) {
            object_.type = SEGBillDetailDoLogicModelType_Data;
            object_.feeType = SEGBillDetailDoLogicModelFeeType_Fee;
            [arrM addObject:object_];
            
            // 统计违约金展示数据
            if ([object_.lfree length] && [object_.lfree floatValue] != 0) {
                SEGOwesMonthDetailModel* data = [[SEGOwesMonthDetailModel alloc] init];
                data = [object_ copy];
                data.type = SEGBillDetailDoLogicModelType_Data;
                data.feeType = SEGBillDetailDoLogicModelFeeType_LFee;
                [arrM addObject:data];
            }
        }
        
        //添加尾部统计数据
        SEGOwesMonthDetailModel* foot = [[SEGOwesMonthDetailModel alloc] init];
        foot.type = SEGBillDetailDoLogicModelType_Foot;
        [arrM addObject:foot];
        
        object.billDetail = arrM;
    }
    
    return data;
}


/**
 请求支付方式列表

 @param finished 回调处理
 */
- (void)requestBillPaymentMethodListFinished:(SEGNetworkReponse)finished {
    [SEGHTTPBusinessManager seg_requestWithMethod:POST URLString:kGetBillPayMethodList parameters:nil finished:^(BOOL isSuccessed, id result, NSString *codeType, NSString *errorMessage) {
        finished(isSuccessed, result, codeType, errorMessage);
    }];
}


/**
 轮询支付方式列表（费用缴纳）

 @param paramas 参数
 @param finished 回调
 */
- (void)requestPollByPayMethodResultWithParamsDic:(NSDictionary*)paramas
                                         Finished:(SEGNetworkReponse)finished {
    [SEGHTTPBusinessManager seg_requestWithMethod:POST URLString:kGetBillPollPayMethodResult parameters:paramas finished:^(BOOL isSuccessed, id result, NSString *codeType, NSString *errorMessage) {
        finished(isSuccessed, result, codeType, errorMessage);
    }];
}

/**
 *  无纸化账单设置
 *
 *  @param finished 网络请求完成后的操作
 */
- (void)dealNoPaper:(NSDictionary*)params finished:(SEGNetworkReponse)finished
{
    [SEGHTTPBusinessManager seg_requestWithMethod:POST
                                        URLString:kSetNoPaperByHouseId
                                       parameters:params
                                         finished:^(BOOL isSuccessed,
                                                    id result,
                                                    NSString *codeType,
                                                    NSString *errorMessage) {
                                             finished(isSuccessed, result, codeType, errorMessage);
                                         }];
}

/**
 *  查询无纸化账单配置
 *
 *  @param finished 网络请求完成后的操作
 */
- (void)checkNoPaper:(NSDictionary*)params finished:(SEGNetworkReponse)finished
{
    [SEGHTTPBusinessManager seg_requestWithMethod:POST
                                        URLString:kGetNoPaperConfig
                                       parameters:params
                                         finished:^(BOOL isSuccessed,
                                                    id result,
                                                    NSString *codeType,
                                                    NSString *errorMessage) {
                                             finished(isSuccessed, result, codeType, errorMessage);
                                         }];
}

/**
 计算时间

 @param intevalMonth 时间间隔的月份
 @return 计算的时间
 */
+ (NSString *)calculateTimeBeseNowWithIntervalMonth:(NSInteger)intevalMonth {
    return [self calculateTimeBase:[self currentTimeString] intervalMonth:intevalMonth];
}

/**
 时间间隔的月份

 @param baseTime 基于哪个时间
 @param intevalMonth 时间间隔的月份
 @return 计算的时间
 */
+ (NSString *)calculateTimeBase:(NSString *)baseTime intervalMonth:(NSInteger)intevalMonth {
    if (baseTime.length < 6) {
        return nil;
    }
    
    NSInteger year = [[baseTime substringToIndex:4] integerValue];
    NSInteger month = [[baseTime substringWithRange:NSMakeRange(4, 2)] integerValue];
    month = month + intevalMonth;
    
    while (month <= 0) {
        year = year - 1;
        month += 12;
    }
    
    while (month > 12) {
        year = year + 1;
        month -= 12;
    }
    
    return [NSString stringWithFormat:@"%ld%02ld", (long)year, (long)month];
}


/**
 当前日期转String

 @return 当前日期转String
 */
+ (NSString *)currentTimeString {
    NSDate *date = [NSDate date];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    formatter.dateFormat = @"yyyyMM";
    return [formatter stringFromDate:date];
}

@end

